<?php

class QB
{
	public $tableName = false;
	public $db = false;
	public $vars = array();
	public $source = false;

	public $limit = false;
	public $offset = false;

	public $orderBy = false;

	const EQUALS = -1;

	const LESSTHEN = -2;
	const GREATERTHEN = -3;

	const CONTAINS = -4;
	const STARTSWITH = -5;
	const ENDSWITH = -6;

	const ISNULL = -7;
	const ISNOTNULL = -8;

	function __construct($tableName,$database)
	{
		$this->tableName = $tableName;
		$this->db = $database;
		$this->source = $_REQUEST;
	}

	function addVar($varName,$varType=self::equals)
	{
		$newVar['name']=$varName;
		$newVar['type']=$varType;

		array_push($this->vars,$newVar);
	}

	function query($infoOnly=false)
	{
		$conditions = array();

		foreach($this->vars as $var)
		{
			if(isset($this->source[$var['name']]))
			{
				$val = $this->source[$var['name']];

				if($val && strlen($val))
				{
					$qVal = DB::escape($this->db,$this->source[$var['name']]);

					switch($var['type'])
					{
						case self::EQUALS :
							$conditions[]="`{$var['name']}` = \"$qVal\"";
							break;

						case self::LESSTHEN :
							$conditions[]="`{$var['name']}` < \"$qVal\"";
							break;

						case self::GREATERTHEN :
							$conditions[]="`{$var['name']}` > \"$qVal\"";
							break;

						case self::CONTAINS :
							$conditions[]="`{$var['name']}` LIKE \"%$qVal%\"";
							break;

						case self::STARTSWITH :
							$conditions[]="`{$var['name']}` LIKE \"$qVal%\"";
							break;

						case self::ENDSWITH  :
							$conditions[]="`{$var['name']}` LIKE \"%$qVal\"";
							break;

						case self::ISNULL :
							$conditions[]="`{$var['name']}` IS NULL";
							break;

						case self::ISNOTNULL :
							$conditions[]="`{$var['name']}` IS NOT NULL";
							break;
					}
				}
			}
		}

		if($infoOnly)
		$query = "SELECT COUNT(*) FROM `{$this->tableName}`";
		else
		$query = "SELECT * FROM `{$this->tableName}`";

		if(count($conditions))
		$query .= " WHERE " . implode(' AND ',$conditions);

		if(is_array($this->orderBy) && count($this->orderBy)>0)
		{
			$orderVars=array();

			foreach($this->orderBy as $orderVar)
			$orderVars[]="`$orderVar`";

			$query .= " ORDER BY ".implode(',',$orderVars);
		}
		else if($this->orderBy)
		$query .= " ORDER BY `{$this->orderBy}`";

		if($this->limit && !$this->offset)
		$query .= " LIMIT {$this->limit}";
		else if($this->limit && $this->offset)
		$query .= " LIMIT {$this->offset},{$this->limit}";
		
//		echo $query;

		return $query;
	}
}
